package com.baidu.recognition.config.baidu;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liuzhiqiang
 */
@Component
public class BaiduApi {

    public static final String TAKEN_URL = "https://openapi.baidu.com/oauth/2.0/token";
    public static final String PRO_API = "https://vop.baidu.com/pro_api";
    public static final String REALTIME_ASR = "wss://vop.baidu.com/realtime_asr?sn=";
    public static final String CREATE = "https://aip.baidubce.com/rpc/2.0/aasr/v1/create";
    public static final String QUERY = "https://aip.baidubce.com/rpc/2.0/aasr/v1/query";
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private BaiduConfig baiduConfig;

    /**
     * @return {
     * "access_token": "1.a6b7dbd428f731035f771b8d********.86400.1292922000-2346678-124328",
     * "expires_in": 86400,
     * "refresh_token": "2.385d55f8615fdfd9edb7c4b********.604800.1293440400-2346678-124328",
     * "scope": "public audio_voice_assistant_get 。。。",
     * "session_key": "ANXxSNjwQDugf8615Onqeik********CdlLxn",
     * "session_secret": "248APxvxjCZ0VEC********aK4oZExMB",
     * }
     */
    public JSONObject getAccessToken() {
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.add("Content-Type", "application/x-www-form-urlencoded");
        MultiValueMap<String, Object> postParameters = new LinkedMultiValueMap<>(2);
        postParameters.add("grant_type", "client_credentials");
        postParameters.add("client_id", BaiduConfig.apiKey);
        postParameters.add("client_secret", BaiduConfig.secretKey);
        HttpEntity<Map> requestEntity = new HttpEntity<>(postParameters, requestHeaders);
        ResponseEntity<JSONObject> entity = restTemplate.exchange(TAKEN_URL, HttpMethod.POST, requestEntity, JSONObject.class);
        return entity.getBody();
    }

    /**
     * 短语音识别极速版
     *
     * @param file
     * @param token {
     *              *     "format":"pcm",
     *              *     "rate":16000,
     *              *     "dev_pid":80001,
     *              *     "channel":1,
     *              *     "token":xxx,
     *              *     "cuid":"baidu_workshop",
     *              *     "len":4096,
     *              *     "speech":"xxx", // xxx为 base64（FILE_CONTENT）
     *              * }
     * @return {"corpus_no":"6433214037620997779","err_msg":"success.","err_no":0,"result":["北京科技馆，"],"sn":"371191073711497849365"}
     */
    public JSONObject speechRecognition(MultipartFile file, String token) {
        byte[] fileByte;
        try {
            fileByte = file.getBytes();
        } catch (IOException e) {
            throw new RuntimeException("文件失败");
        }
        String voiceBase64 = Base64.getEncoder().encodeToString(fileByte);
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.add("Content-type", "application/json; charset=utf-8");
        Map<String, Object> body = new HashMap<>(8);
        body.put("format", "pcm");
        body.put("rate", 16000);
        body.put("dev_pid", 80001);
        body.put("channel", 1);
        body.put("token", token);
        body.put("cuid", "baidu_workshop");
        body.put("len", file.getSize());
        body.put("speech", voiceBase64);
        HttpEntity<Map> requestEntity = new HttpEntity<>(body, requestHeaders);
        ResponseEntity<JSONObject> entity = restTemplate.exchange(PRO_API, HttpMethod.POST, requestEntity, JSONObject.class);
        return entity.getBody();
    }

    public JSONObject createTask(String speechUrl) {
        JSONObject jsonObject = getAccessToken();
        String token = jsonObject.getString("access_token");
        String url = CREATE + "?access_token=" + token;
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.add("Content-type", "application/json; charset=utf-8");
        Map<String, Object> body = new HashMap<>(4);
        body.put("format", "pcm");
        body.put("rate", 16000);
        body.put("pid", 80001);
        body.put("speech_url", speechUrl);
        HttpEntity<Map> requestEntity = new HttpEntity<>(body, requestHeaders);
        ResponseEntity<JSONObject> entity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, JSONObject.class);
        return entity.getBody();

    }

    public JSONObject queryTask(List taskIds) {
        JSONObject jsonObject = getAccessToken();
        String token = jsonObject.getString("access_token");
        String url = QUERY + "?access_token=" + token;
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.add("Content-type", "application/json; charset=utf-8");
        Map<String, Object> body = new HashMap<>(1);
        body.put("task_ids", taskIds);
        HttpEntity<Map> requestEntity = new HttpEntity<>(body, requestHeaders);
        ResponseEntity<JSONObject> entity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, JSONObject.class);
        return entity.getBody();

    }
}
